/*
* INSANE - Interactive Structural Analysis Environment
*
* Copyright (C) 2003-2005
* Universidade Federal de Minas Gerais
* Escola de Engenharia
* Departamento de Engenharia de Estruturas
* 
* Author's email :    insane@dees.ufmg.br
* Author's website :  http://www.dees.ufmg.br/insane
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
package br.ufmg.dees.insane.ui.rich.full.dialogs;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import br.ufmg.dees.insane.commons.dialogs.DecimalField;
import br.ufmg.dees.insane.commons.dialogs.SimpleDialog;
import br.ufmg.dees.insane.materialMedia.material.LinearElasticIsotropic;
import br.ufmg.dees.insane.materialMedia.material.Material;
import br.ufmg.dees.insane.model.disc.element.Element;
import br.ufmg.dees.insane.model.disc.fem.FemModel;
import br.ufmg.dees.insane.ui.rich.full.InsaneInternalInterface;

/**
 * A class representing creation dialog on screen.
 * For example:
 * <pre>
 *    ElmMaterialDialog dgl = new ElmMaterialDialog(parent);
 *    dgl.pack();
 * </pre>
 *
 * @author Fonseca, Flavio & Pitangueira, Roque
 * @see gui.InsaneInternalInterface
 * @since April 2004
 */
public final class ElmMaterialDialog extends SimpleDialog {
	
	/**
	 * Comment for <code>serialVersionUID</code>
	 */
	private static final long serialVersionUID = 1L;
	private InsaneInternalInterface parent;
	private NumberFormat numberFormat;
	private NumberFormat numberFormat2;
	private FemModel fmodel;
	
	private JPanel matButPane = new JPanel();
	private String[] matLabelList;
	private JComboBox matListCombo = new JComboBox();
	private DecimalField matEField;
	private DecimalField matGField;
	private DecimalField matPoissonField;
	private DecimalField matThermalField;
	public String matLabel;
	
	/**
	 * Constructor method, calling super with the especific title.
	 *
	 * @param parent The parent of the class.
	 * @see gui.InsaneInternalInterface
	 */
	public ElmMaterialDialog(InsaneInternalInterface parent) {
		this.parent = parent;
		fmodel = parent.getModel().getDiscreteModel();
		
		setUpMaterialsList();
		setUpMaterialsCombo();
		
		setUpFormat();
		setUpFields();
		
		//Setting subpanel material
		JPanel materialPane = new JPanel();
		materialPane.setLayout(new BoxLayout(materialPane, BoxLayout.Y_AXIS));
        materialPane.setMaximumSize(new Dimension(500,155));
		materialPane.setBorder(BorderFactory.createCompoundBorder(
			BorderFactory.createTitledBorder(parent.getResourceBundle().getString("dMatDialog01")),
			BorderFactory.createEmptyBorder(2,2,2,2)));
		
		matListCombo.setMaximumSize(new Dimension(300,26));
		matListCombo.setPreferredSize(new Dimension(300,26));
		matListCombo.setMinimumSize(new Dimension(300,26));
		matListCombo.setSize(new Dimension(300,26));
		
		matListCombo.setMaximumRowCount(5);
		
		matListCombo.addItemListener(new MatComboListener());
		matGField.addFocusListener(new MatGListener());
		matPoissonField.addFocusListener(new MatPoissonListener());
		
		matEField.setEditable(false);
		matGField.setEditable(false);
		matPoissonField.setEditable(false);
		matThermalField.setEditable(false);
		
		matButPane.add(matListCombo);
		
		JPanel matPropPane = new JPanel();
		matPropPane.setLayout(new GridLayout(2,2,2,2));
		
		JPanel matEPane = new JPanel();
		JPanel matGPane = new JPanel();
		JPanel matPoissonPane = new JPanel();
		JPanel matThermalPane = new JPanel();
		
		matEPane.add(new JLabel("E:"));
		matEPane.add(matEField);
		matGPane.add(new JLabel("G:"));
		matGPane.add(matGField);
		matPoissonPane.add(new JLabel(" \u03BD:"));
		matPoissonPane.add(matPoissonField);
		matThermalPane.add(new JLabel("\u03B1:"));
		matThermalPane.add(matThermalField);
		matPropPane.add(matEPane);
		matPropPane.add(matGPane);
		matPropPane.add(matPoissonPane);
		matPropPane.add(matThermalPane);
		
		materialPane.add(matButPane);
		materialPane.add(matPropPane);
		
		setPane(materialPane);
		
    }
	
//*****************************************************************************
	
    public int showDialog() {
    	return super.showDialog(parent, parent.getResourceBundle().getString("dMatDialog02"));
    }
	
//*****************************************************************************
	
	/**
	 * This method is executed on OK button click.
	 */
	public void approvedPerform() {
		
		try {
			
			int matIndex = matListCombo.getSelectedIndex();
			if (matIndex>0)
				matLabel = ((LinearElasticIsotropic)fmodel.getMaterialsList().get(matIndex-1)).getLabel();
			else matLabel = null;
			
		} catch (Exception e) {
			Toolkit.getDefaultToolkit().beep();
			this.setVisible(false);
		}
	}
	
//*****************************************************************************
	
	/**
	 * Sets up the number formater
	 */
	private void setUpFormat() {
		numberFormat = (DecimalFormat)NumberFormat.getNumberInstance(Locale.UK);
		numberFormat.setMinimumFractionDigits(parent.getModelState().getPrecision());
		numberFormat.setMaximumFractionDigits(8);
		
		numberFormat2 = (DecimalFormat)NumberFormat.getNumberInstance(Locale.UK);
		numberFormat2.setMinimumFractionDigits(parent.getModelState().getPrecision());
		numberFormat2.setMaximumFractionDigits(parent.getModelState().getPrecision());
	}
	
//*****************************************************************************
	
	/**
	 * Sets up fields
	 */
	private void setUpFields() {
		
		if (this.parent.getController().getSelection().size() == 1 ) {
			
			Element elm = (Element)this.parent.getController().getSelection().get(0);
			
			String str;
			
			//Setting material fields
			if (elm.getMaterial() != null)
				str = elm.getMaterial().getLabel();
			else str = "";
			int num = fmodel.getNumberOfMaterials();
			int matIndex = 0;
			for (int i=0; i<num; i++) {
				if (str.equals(matLabelList[i+1]))
					matIndex = i+1;
			}
			matListCombo.setSelectedIndex(matIndex);
			try {
			    LinearElasticIsotropic mat = (LinearElasticIsotropic)elm.getMaterial();
				matEField = new DecimalField(mat.getMaterialValues(mat.ELASTICITY).doubleValue(), 7, numberFormat);
				matGField = new DecimalField(mat.getMaterialValues(mat.SHEAR_MODULUS).doubleValue(), 7, numberFormat);
				matPoissonField = new DecimalField(mat.getMaterialValues(mat.POISSON).doubleValue(), 7, numberFormat);
				matThermalField = new DecimalField(mat.getMaterialValues(mat.THERMAL_COEFF).doubleValue(), 7, numberFormat);
			} catch (Exception e) {
				matEField = new DecimalField(0, 7, numberFormat);
				matGField = new DecimalField(0, 7, numberFormat);
				matPoissonField = new DecimalField(0, 7, numberFormat);
				matThermalField = new DecimalField(0, 7, numberFormat);
				matEField.setText(" ");
				matGField.setText(" ");
				matPoissonField.setText(" ");
				matThermalField.setText(" ");
			}
			
		} else {
			
			//Setting material fields
			matEField = new DecimalField(0, 7, numberFormat);
			matGField = new DecimalField(0, 7, numberFormat);
			matPoissonField = new DecimalField(0, 7, numberFormat);
			matThermalField = new DecimalField(0, 7, numberFormat);
			matListCombo.setSelectedIndex(0);
			matEField.setText(" ");
			matGField.setText(" ");
			matPoissonField.setText(" ");
			matThermalField.setText(" ");
			
		}
		
	}
	
//*****************************************************************************
	
	public void setUpMaterialsList() {
		
		int num = fmodel.getNumberOfMaterials();
		
		if (num > 0) {
			matLabelList = new String[num+1];
			matLabelList[0] = "----- " + parent.getResourceBundle().getString("dMatDialog03") + " -----";
			for (int i=0; i<num; i++)
				matLabelList[i+1] = ((Material)parent.getModel().getDiscreteModel().getMaterialsList().get(i)).getLabel();
		}else {
			matLabelList = new String[1];
			matLabelList[0] = "----- " + parent.getResourceBundle().getString("dMatDialog04") + " -----";
		}
		
	}
	
//*****************************************************************************
	
	public void setUpMaterialsCombo() {
		
		matListCombo.removeAllItems();
		for (int i=0; i<matLabelList.length; i++)
			matListCombo.addItem(matLabelList[i]);
		
	}
	
//*****************************************************************************
	
	/** Private inner class to handle button events. */
	private class MatComboListener implements ItemListener {
		public void itemStateChanged(ItemEvent evt) {
			
			int index = matListCombo.getSelectedIndex();
			
			if (index > 0 ) {
				
			    LinearElasticIsotropic material = (LinearElasticIsotropic)fmodel.getMaterialsList().get(index-1);
				
				matEField.setValue(material.getMaterialValues(material.ELASTICITY).doubleValue());
				matGField.setValue(material.getMaterialValues(material.SHEAR_MODULUS).doubleValue());
				matPoissonField.setValue(material.getMaterialValues(material.POISSON).doubleValue());
				matThermalField.setValue(material.getMaterialValues(material.THERMAL_COEFF).doubleValue());
				
			} else {
				
				matEField.setText(" ");
				matGField.setText(" ");
				matPoissonField.setText(" ");
				matThermalField.setText(" ");
				
			}
			
		}
	}
	
//*****************************************************************************
	
	/** Private inner class to handle button events. */
	private class MatGListener implements FocusListener {
		
		public void focusGained(FocusEvent evt) {}
		
		public void focusLost(FocusEvent evt) {
			double g = matGField.getValue();
			double e = matEField.getValue();
			double p = e / (2*g) - 1;
			if ( g!=0 && e!=0 && (p<0 || p>0.5)) {
				JOptionPane.showMessageDialog(parent,
					parent.getResourceBundle().getString("dMatDialog10") + " (\u03BD = " + numberFormat2.format(p) + ")",
					parent.getResourceBundle().getString("cmError"), JOptionPane.ERROR_MESSAGE);
				matGField.setValue(0);
				matGField.setText(parent.getResourceBundle().getString("gmInvalidData"));
			}
			if (p>=0 && p<=0.5 && e!=0) {
				matPoissonField.setValue(p);
				matPoissonField.setText(numberFormat2.format(p));
			}
		}
		
	}
	
//*****************************************************************************
	
	/** Private inner class to handle button events. */
	private class MatPoissonListener implements FocusListener {
		
		public void focusGained(FocusEvent evt) {}
		
		public void focusLost(FocusEvent evt) {
			double p = matPoissonField.getValue();
			if (p<0 || p>0.5) {
				JOptionPane.showMessageDialog(parent,
					parent.getResourceBundle().getString("dMatDialog11") + "\n                          0.0 \u2264 \u03BD \u2264 0.5",
					parent.getResourceBundle().getString("cmError"), JOptionPane.ERROR_MESSAGE);
				matPoissonField.setValue(0);
				matPoissonField.setText(parent.getResourceBundle().getString("gmInvalidData"));
			} else {
				double e = matEField.getValue();
				if (e!=0) {
					double g = e / (2*(1+p));
					if (p>=0 && p<=0.5) {
						matGField.setValue(g);
						matGField.setText(numberFormat2.format(g));
					}
				}
			}
		}
		
	}
	
//*****************************************************************************
}

